package com.lv.suyiyong.hfr.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lv.common.base.BaseActivity
import com.lv.common.imp.UploadFileListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.*
import com.lv.common.utils.picengine.CompressEngine
import com.lv.common.utils.picengine.CropWHEngine
import com.lv.common.utils.picengine.GlideEngine

import com.lv.service.bean.UserInfoOld
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.ui.INPUT_ENUM
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.ActivityUserinfoBinding
import kotlinx.coroutines.*
import okhttp3.RequestBody
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/6 10:33 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：个人信息
 */
@Route(path = ARoutUtils.UserInfoActivity)
class UserInfoActivity : BaseActivity<ActivityUserinfoBinding>(),
    View.OnClickListener {
    @Autowired(name = "userinfo")
    @JvmField
    var mUserInfo: UserInfo? = null

    private val mBeans = mutableListOf<LocalMedia?>()
    private var mCpyid: String? = YgxSpUtils.getString(Constants.KEY_CPYID)
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val viewModel: ServiceViewModel by viewModel()
    override fun getLayoutRes() = R.layout.activity_userinfo
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@UserInfoActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            titleBar.setTitle("个人信息")
            llLogo.setOnClickListener(this@UserInfoActivity)
            llName.setOnClickListener(this@UserInfoActivity)
            llPhone.setOnClickListener(this@UserInfoActivity)
            llPassword.setOnClickListener(this@UserInfoActivity)
            userInfo = mUserInfo
        }
    }


    override fun initConfig() {
        super.initConfig()
//        UserDbHelper.getLiveUserInfo(this@UserInfoActivity).observeKt {
//            mUserInfo = it
//            mBinding.userInfo = mUserInfo
//        }


    }


    override fun initData() {
        super.initData()
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {

            R.id.ll_logo -> {
                checkPermission()
            }

            R.id.ll_name -> {
                ARouter.getInstance().build(ARoutUtils.InputCommonActivity)
                    .withString("title", "昵称")
                    .withInt("length", 20)
                    .withString("content", mUserInfo?.nickname)
                    .withSerializable("inputState", INPUT_ENUM.SINGLE)
                    .navigation(this, 1)
            }

            R.id.ll_phone -> {
                ARouter.getInstance().build(ARoutUtils.ChangePhoneActivity)
                    .withParcelable("userinfo", mUserInfo).navigation()
            }

            R.id.ll_password -> {
                ARouter.getInstance().build(ARoutUtils.ChangePasswordActivity)
                    .withParcelable("userinfo", mUserInfo).navigation()
            }


        }
    }

    private fun checkPermission() {
        val permissions = mutableListOf(
            Manifest.permission.CAMERA,
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
//            permissions.add(Manifest.permission.READ_MEDIA_AUDIO)
//            permissions.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }



        PermissionXUtils.checkPermissBefore(
            this,
            permissions,
            "请授予相机、存储权限，以便使用相机拍摄或在手机相册中选择图片",
            callback = object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        showPicSelector()
                    }
                }
                override fun fotPermsission() {

                }
            })
    }

    private fun showPicSelector() {
        val createCropEngine = CropWHEngine.createCropEngine()
        createCropEngine.setRatio("1:1", 1.0f, 1.0f)
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())//图库显示的类型
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(CompressEngine.createCompressEngine())
            .setCropEngine(createCropEngine)
            .setMaxSelectNum(1)//最大图片数
//            .setMaxVideoSelectNum(1)//最大视频数
            .setMinSelectNum(1)
            .setImageSpanCount(4)
            .isMaxSelectEnabledMask(true)//不可点击时，是否显示朦层
            .isPreviewImage(true) // 是否可预览图片
            .isDisplayCamera(true) // 是否显示拍照按钮
            .isOriginalSkipCompress(true) // 是否压缩
            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//            .setSelectedData(mBeans)
//            .isWithSelectVideoImage(false)//是否可以同时选择视频和图片
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    mBeans.clear()
                    result?.let {
                        if (result.isNotEmpty()) {
                            mBeans.addAll(result)
                            logoToNet()
                        }
                    }

                }

                override fun onCancel() {}
            })


    }

    private fun logoToNet() {
        startLoading("上传中……")
        val mMedias = mutableListOf<LocalMedia?>()
        mMedias.addAll(mBeans)
        lifecycleScope.launchWhenCreated {
            withContext(Dispatchers.IO) {
                YgxNetUtilsKt.partFilesToAli(
                    this@UserInfoActivity, mSelectMedia = mMedias, uploadFileListener =
                        object : UploadFileListener {
                            override fun uploadSuccess(list: List<String>, listString: String) {
                                super.uploadSuccess(list, listString)
                                upPic(listString)
                            }

                            override fun uploadFailed(message: String) {
                                super.uploadFailed(message)
                                loadFinished()
                            }
                        })
            }
        }
//        LogUtils.e(mImages)
//        return aaa.toString()
    }

    private fun upPic(listString: String) {
        val partMap = mutableMapOf<String, RequestBody>()
        partMap["image"] = YgxNetUtilsKt.partToRequestBody(listString)
        partMap["cpyid"] = YgxNetUtilsKt.partToRequestBody(mCpyid ?: "")
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { viewModel.updateMyMessage(partMap) }.await()
            parseResult(result, 1)
        }
    }

    private fun upName(name: String) {
        startLoading()
        val partMap = mutableMapOf<String, RequestBody>()
        partMap["cpyid"] = YgxNetUtilsKt.partToRequestBody(mCpyid ?: "")
        partMap["name"] = YgxNetUtilsKt.partToRequestBody(name)
        lifecycleScope.launchWhenCreated {
            this.launch {
                val result: DataResult<BaseYgxRsp> =
                    myScope.async { viewModel.updateMyMessage(partMap) }.await()
                parseResult(result, 0)
            }
        }
    }

    /**
     * @param type 0 Name
     */
    private fun parseResult(data: DataResult<BaseYgxRsp>, type: Int) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfoOld> { code, data, message, result ->
                data?.let {
                    mUserInfo?.let {
                        when (type) {
                            0 -> {
                                mUserInfo?.nickname = data.nickname ?: ""
                            }

                            1 -> {
                                mUserInfo?.logo = data.logo
                            }

                        }
                        UserDbHelper.UpDataUserInfo(this@UserInfoActivity, mUserInfo!!)
                        mBinding.userInfo = mUserInfo
                    }
                }

            }
            onBizError<UserInfo> { code, message, data ->
                showToast(message)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                1 -> {
                    val name = data.getStringExtra("content")
                    if (!name.isNullOrEmpty() && name != mUserInfo?.name) {
                        upName(name)
                    }
                }
            }
        }
    }

}